const Express = require("express");
const router = Express.Router();
const os = require("os");
const multer = require("multer");
const path = require("path");
const ResponseHelper = require("../ResponseHelper");
const allowedMimetype = ["application/pdf"];

function fileFilter(req, file, cb) {
  // 这个函数应该调用 `cb` 用boolean值来指示是否应接受该文件
  if (allowedMimetype.includes(file.mimetype)) {
    //接受这个文件，使用`true`，像这样:
    cb(null, true);
  } else {
    // 拒绝这个文件，使用`false`，像这样:
    cb(new Error("Reject this type of picture"));
  }
}

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    console.log("================params", JSON.parse(req.params.id));
    const params = JSON.parse(req.params.id);
    let uploadPath = "C:\\pdfdata";
    const system = os.platform();
    if (system === "linux") {
      if (params.type === "local") {
        uploadPath = `/home/cobot/pdfdata`;
      } else if (params != "local") {
        uploadPath = `${params.address}:`;
      }
    } else {
      if (params.type === "local") {
        uploadPath = `C:\\pdfdata`;
      } else if (params != "local") {
        uploadPath = `${params.address}:`;
      }
    }
    console.log("================uploadPath", uploadPath);
    cb(null, uploadPath);
  },

  filename: function (req, file, cb) {
    // const fileName = Math.random().toString(36).slice(-8);
    // const timeSamp = Date.now();
    const params = JSON.parse(req.params.id);
    let ext = path.extname(file.originalname);
    if (!ext && file.mimetype == "application/pdf") {
      ext = ".pdf";
    }
    const name = params.name ? `${params.name}${ext}` : `${fileName}_${timeSamp}${ext}`
    cb(null, name);
  },
});
const upload = multer({
  storage: storage,
  limits: { fileSize: 1024 * 1024 * 10 },
  fileFilter,
});
router.post("/:id", upload.single("file"), async (req, res, next) => {
  try {
    ResponseHelper.sendData('导出成功！', res);
  } catch (err) {
    ResponseHelper.sendData(err, res);
  }
});

module.exports = router;
